package com.waimai1.waimai.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.waimai1.waimai.common.R;
import com.waimai1.waimai.common.Utils;
import com.waimai1.waimai.entity.MyOrder;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.HwOrderService;
import com.waimai1.waimai.service.MHService;
import com.waimai1.waimai.service.MyOrderService;
import com.waimai1.waimai.service.WepayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service()
public class MHServiceImpl implements MHService {
    @Autowired
    public RedisTemplate<String, String> redisTemplate;
    @Value("${MH.notifyUrl}")
    private String notifyUrl;
    @Autowired
    private WepayService wepayService;
    @Autowired
    private MyOrderService myOrderService;
    @Autowired
    private HwOrderService hwOrderService;

    private String getToken(String time) {
        Map<String, String> argsMap = new TreeMap<>();
        argsMap.put("username", Utils.MHName);
        argsMap.put("password", Utils.MHPassword);
        MultipartBodyBuilder builder = new MultipartBodyBuilder();
        for (Map.Entry<String, String> entry : argsMap.entrySet()) {
            builder.part(entry.getKey(), entry.getValue());
        }
        //     http接口调用web
        WebClient webClient = WebClient.builder()
                .defaultHeader("Content-Type", "application/json")
                .defaultHeader("channelid", Utils.MHId)
                .defaultHeader("txntime", time)
                .baseUrl(Utils.mhUrl.get("MH_TOKEN"))
                .codecs(obj -> obj.defaultCodecs().maxInMemorySize(10 * 1024 * 1024)).build();
        log.info(webClient.toString());
        Mono<Object> result = webClient.post()
                .body(BodyInserters.fromValue(argsMap))
                .retrieve()
                .bodyToMono(Object.class);
        Map<String, Object> resObj = (Map<String, Object>) result.block();
        if (!"000000".equals(resObj.get("rtnCode"))) {
            log.info("resObj:{}", resObj);
            throw new NotErrorException(1007, "MHtoken 获取失败");
        }
        return ((Map<String, String>) resObj.get("rtnData")).get("token");
    }

    @Override
//    public String getSign(TreeMap<String,Object> argsMap,String time) {
    public String getSign(String argsMapJson, String time) {

        String stringSignTemp = argsMapJson + Utils.MHKey + time;

        String sign = DigestUtils.md5DigestAsHex(stringSignTemp.getBytes(StandardCharsets.UTF_8));
        return sign;
    }

    @Override
    public Object getData(Map<String, Object> argsMap, String url, String time) {
        log.info("getData argsMap:{}", argsMap);
        log.info("getData url:{}", url);
        log.info("Utils.MHDevCode :{}", Utils.MHDevCode);
        //     判断token是否过期，过期则重新获取
        String MHToken = redisTemplate.opsForValue().get("MHToken");
        if (null == MHToken) {
            MHToken = getToken(time);
            redisTemplate.opsForValue().set("MHToken", MHToken);
            redisTemplate.expire("MHToken", 30, TimeUnit.MINUTES);
        }
        String sign = getSign(JSON.toJSONString(argsMap), time);
//     http接口调用web
        WebClient webClient = WebClient.builder()
                .defaultHeader("Content-Type", "application/json")
                .defaultHeader("token", MHToken)
                .defaultHeader("channelid", Utils.MHId)
                .defaultHeader("sign", sign)
                .defaultHeader("devCode", Utils.MHDevCode)
                .defaultHeader("txntime", time)
                .baseUrl(url)
                .codecs(obj -> obj.defaultCodecs().maxInMemorySize(10 * 1024 * 1024)).build();
        Mono<Object> result = webClient.post()
                .body(BodyInserters.fromValue(argsMap))//json传递
                .retrieve()
                .bodyToMono(Object.class);
        Object resObj = result.block();
        return resObj;
    }

    @Override
    public void createOrder(MyOrder order) {
        String time = String.valueOf(new Date().getTime());
        Map<String, Object> argsMap = new HashMap<String, Object>();
        argsMap.put("floorPrice", order.getTotalPrice());//设置底线价格为用户实际支付避免亏本，当产品的放单总价高于此价格，订单将关闭
        String url = "";
        List<Map<String, Object>> goods = new ArrayList<>();
        List<Map> maps = new ArrayList<>();
        switch (order.getMovieName()) {
            case "奈雪的茶":
                url = "NX";
                argsMap.put("outId", order.getId());
                argsMap.put("storeId", order.getRestaurantId());
                argsMap.put("phoneNo", order.getTakePhone());
                argsMap.put("callBackUrl", notifyUrl);

                if ("EAT_IN".equals(order.getEatType())) {//堂食
                    argsMap.put("packFlag", 0);
                } else if ("TAKE_AWAY".equals(order.getEatType())) {//打包
                    argsMap.put("packFlag", 1);
                } else if ("WaiMai".equals(order.getEatType())) {//外送
                    argsMap.put("packFlag", 2);
                    JSONObject jsonObject = JSON.parseObject(order.getReceiveInfo());
                    argsMap.put("receiverName", jsonObject.get("receiverName"));
                    argsMap.put("receiverAddress", jsonObject.get("receiverAddress"));
                    argsMap.put("receiverLng", jsonObject.get("receiverLng"));
                    argsMap.put("receiverLat", jsonObject.get("receiverLat"));
                    argsMap.put("phoneNo", jsonObject.get("receiverPhone"));
                }
                // 将JSON字符串转换为Map的List
                maps = JSON.parseArray(order.getSeat(), Map.class);
                maps.forEach(seat -> {
                    Map<String, Object> good = new HashMap<String, Object>();
                    good.put("count", seat.get("amount"));
                    good.put("itemId", seat.get("product_id"));
                    Object childLinkId = seat.get("childLinkId");
                    if (childLinkId != null) {
                        good.put("skuCode", childLinkId);
                    }
                    //TODO 星巴克的定制属性较为复杂，暂时先不做了
//                    Object options = seat.get("options");
//                    if(options!=null){
//                        good.put("addExtra", options);
//                    }
                    goods.add(good);
                });
                argsMap.put("goods", goods);
                System.out.println("==============");
                System.out.println(argsMap);
                System.out.println("==============");
                break;
            case "星巴克":
                url = "XBK";
                argsMap.put("outId", order.getId());
                argsMap.put("storeId", order.getRestaurantId());
                argsMap.put("phoneNo", order.getTakePhone());
                argsMap.put("callBackUrl", notifyUrl);

                if ("EAT_IN".equals(order.getEatType())) {//堂食
                    argsMap.put("model", 0);
                } else if ("TAKE_AWAY".equals(order.getEatType())) {//打包
                    argsMap.put("model", 1);
                } else if ("WaiMai".equals(order.getEatType())) {//外送
                    argsMap.put("model", 2);
                    JSONObject jsonObject = JSON.parseObject(order.getReceiveInfo());
                    argsMap.put("receiverName", jsonObject.get("receiverName"));
                    argsMap.put("receiverAddress", jsonObject.get("receiverAddress"));
                    argsMap.put("receiverLng", jsonObject.get("receiverLng"));
                    argsMap.put("receiverLat", jsonObject.get("receiverLat"));
                    argsMap.put("phoneNo", jsonObject.get("receiverPhone"));
                }
                // 将JSON字符串转换为Map的List
                maps = JSON.parseArray(order.getSeat(), Map.class);
                maps.forEach(seat -> {
                    Map<String, Object> good = new HashMap<String, Object>();
                    good.put("num", seat.get("amount"));
                    good.put("productId", seat.get("product_id"));
                    Object childLinkId = seat.get("childLinkId");
                    if (childLinkId != null) {
                        good.put("skuId", childLinkId);
                    }
                    //TODO 星巴克的定制属性较为复杂，暂时先不做了
//                    Object options = seat.get("options");
//                    if(options!=null){
//                        good.put("addExtra", options);
//                    }
                    goods.add(good);
                });
                argsMap.put("goods", goods);
                System.out.println("==============");
                System.out.println(argsMap);
                System.out.println("==============");
                break;
            case "肯德基":
                url = "KFC";
                argsMap.put("outId", order.getId());
                argsMap.put("storeCode", order.getRestaurantId());
                argsMap.put("phoneNo", order.getTakePhone());
                argsMap.put("callBackUrl", notifyUrl);
                if ("EAT_IN".equals(order.getEatType())) {//堂食
                    argsMap.put("model", 0);
                } else if ("TAKE_AWAY".equals(order.getEatType())) {//打包
                    argsMap.put("model", 1);
                } else if ("WaiMai".equals(order.getEatType())) {//外送
                    argsMap.put("model", 2);
                    JSONObject jsonObject = JSON.parseObject(order.getReceiveInfo());
                    argsMap.put("receiverName", jsonObject.get("receiverName"));
                    argsMap.put("receiverAddress", jsonObject.get("receiverAddress"));
                    argsMap.put("receiverLng", jsonObject.get("receiverLng"));
                    argsMap.put("receiverLat", jsonObject.get("receiverLat"));
                    argsMap.put("phoneNo", jsonObject.get("receiverPhone"));
                }
                // 将JSON字符串转换为Map的List
                maps = JSON.parseArray(order.getSeat(), Map.class);
                maps.forEach(seat -> {
                    Map<String, Object> good = new HashMap<String, Object>();
                    good.put("quantity", seat.get("amount"));
                    good.put("linkId", seat.get("product_id"));
                    Object childLinkId = seat.get("childLinkId");
                    if (childLinkId != null) {//多规格产品必传
                        good.put("childLinkId", childLinkId);
                    }
                    Object options = seat.get("options");
                    if (options != null) {//套餐必传
                        good.put("condimentItems", options);
                    }
                    goods.add(good);
                });
                argsMap.put("goods", goods);
                System.out.println("==============");
                System.out.println(argsMap);
                System.out.println("==============");
                break;
            case "麦当劳":
                url = "MCD";
                argsMap.put("outId", order.getId());
                argsMap.put("storeCode", order.getRestaurantId());
                argsMap.put("phoneNo", order.getTakePhone());
                argsMap.put("callBackUrl", notifyUrl);
                if ("EAT_IN".equals(order.getEatType())) {//堂食
                    argsMap.put("model", 0);
                } else if ("TAKE_AWAY".equals(order.getEatType())) {//打包
                    argsMap.put("model", 1);
                } else if ("WaiMai".equals(order.getEatType())) {//外送
                    argsMap.put("model", 2);
                    JSONObject jsonObject = JSON.parseObject(order.getReceiveInfo());
                    argsMap.put("receiverName", jsonObject.get("receiverName"));
                    argsMap.put("receiverAddress", jsonObject.get("receiverAddress"));
                    argsMap.put("receiverLng", jsonObject.get("receiverLng"));
                    argsMap.put("receiverLat", jsonObject.get("receiverLat"));
                    argsMap.put("phoneNo", jsonObject.get("receiverPhone"));
                }
                // 将JSON字符串转换为Map的List
                maps = JSON.parseArray(order.getSeat(), Map.class);
                maps.forEach(seat -> {
                    Map<String, Object> good = new HashMap<String, Object>();
                    good.put("quantity", seat.get("amount"));
                    good.put("code", seat.get("product_id"));
                    Object options = seat.get("options");
                    if (options != null) {
                        good.put("comboItems", options);
                    }
                    goods.add(good);
                });
                argsMap.put("goods", goods);
                System.out.println("==============");
                System.out.println(argsMap);
                System.out.println("==============");
                break;
            case "瑞幸咖啡":
                url = "LK";
                argsMap.put("outId", order.getId());
                argsMap.put("storeCode", order.getRestaurantId());
                argsMap.put("phoneNo", order.getTakePhone());
                argsMap.put("callBackUrl", notifyUrl);
                if ("EAT_IN".equals(order.getEatType())) {//堂食
                    argsMap.put("model", 0);
                } else if ("TAKE_AWAY".equals(order.getEatType())) {//打包
                    argsMap.put("model", 1);
                } else if ("WaiMai".equals(order.getEatType())) {//外送
                    argsMap.put("model", 2);
                    JSONObject jsonObject = JSON.parseObject(order.getReceiveInfo());
                    argsMap.put("receiverName", jsonObject.get("receiverName"));
                    argsMap.put("receiverAddress", jsonObject.get("receiverAddress"));
                    argsMap.put("receiverLng", jsonObject.get("receiverLng"));
                    argsMap.put("receiverLat", jsonObject.get("receiverLat"));
                    argsMap.put("phoneNo", jsonObject.get("receiverPhone"));
                }
                // 将JSON字符串转换为Map的List
                maps = JSON.parseArray(order.getSeat(), Map.class);
                maps.forEach(seat -> {
                    Map<String, Object> good = new HashMap<String, Object>();
                    good.put("num", seat.get("amount"));
                    good.put("productId", seat.get("product_id"));
                    Object childLinkId = seat.get("childLinkId");
                    if (childLinkId != null) {
                        good.put("skuCode", childLinkId);
                    }
                    goods.add(good);
                });
                argsMap.put("goods", goods);
                System.out.println("==============");
                System.out.println(argsMap);
                System.out.println("==============");
                break;

            case "必胜客":
                url = "PZH";
                argsMap.put("outId", order.getId());
                argsMap.put("storeCode", order.getRestaurantId());
                argsMap.put("phoneNo", order.getTakePhone());
                argsMap.put("callBackUrl", notifyUrl);
                if ("EAT_IN".equals(order.getEatType())) {//堂食
                    argsMap.put("orderType", 0);
                } else if ("TAKE_AWAY".equals(order.getEatType())) {//打包
                    argsMap.put("orderType", 1);
                } else if ("WaiMai".equals(order.getEatType())) {//外送
                    argsMap.put("model", 2);
                    JSONObject jsonObject = JSON.parseObject(order.getReceiveInfo());
                    argsMap.put("receiverName", jsonObject.get("receiverName"));
                    argsMap.put("receiverAddress", jsonObject.get("receiverAddress"));
                    argsMap.put("receiverLng", jsonObject.get("receiverLng"));
                    argsMap.put("receiverLat", jsonObject.get("receiverLat"));
                    argsMap.put("phoneNo", jsonObject.get("receiverPhone"));
                }
                // 将JSON字符串转换为Map的List
                maps = JSON.parseArray(order.getSeat(), Map.class);
                maps.forEach(seat -> {
                    Map<String, Object> good = new HashMap<String, Object>();
                    good.put("linkId", seat.get("product_id"));
                    Object options = seat.get("options");
                    if (options != null) {
                        good.put("mealRoundList", options);
                    }
                    goods.add(good);
                });
                argsMap.put("goods", goods);
                System.out.println("==============");
                System.out.println(argsMap);
                System.out.println("==============");
                break;
            default:
                log.info("没有匹配异常结束");
                return;
        }
        url = "MH_" + url + "_PUT";
        log.info("argsMap:{}", argsMap.toString());
        Map<String, Object> res = (Map<String, Object>) getData(argsMap, Utils.mhUrl.get(url), time);
        log.info("res:{}", res.toString());
        if (!"000000".equals(res.get("rtnCode"))) {
            //自动退款，不在人工审核
            order.setHwStatus("出单失败");
            order.setStatus(Utils.STATUS_REFUNDED);
            wepayService.allRefund(order);
            myOrderService.updateById(order);
            throw new NotErrorException(1008, res.get("rtnCode") + (String) res.get("rtnMsg"));
        } else {
            order.setHwStatus("出单中");
            //修改订单状态
            myOrderService.updateById(order);
        }
    }
    //麻花的PP回调接口
    public Object mhPPNotify(Map<String, Object> map) throws JsonProcessingException, IllegalAccessException, NoSuchFieldException, InstantiationException, ParseException {
        //查询订单
        MyOrder order = myOrderService.getById((String) map.get("outId"));
        if(order == null){
            return "订单不存在";
        }
        if("奈雪的茶".equals(order.getMovieName())){//奈雪的查询不一样
            Integer putStatus = (Integer) map.get("putStatus");
            order.setRefundPrice((Double) map.get("refundAmount"));
            Double refundAmount = (Double) map.get("refundAmount");
            Double totalAmount = (Double) map.get("totalAmount");
            if(refundAmount.doubleValue()==totalAmount.doubleValue()) {//如果退款等于平台拿货价
                order.setRefundPrice(order.getTotalPrice());//设置应退款总金额为实付款
            }else {
                order.setRefundPrice(refundAmount);
            }
            //如果取餐码有值，设置值
            Object takeCode = map.get("takeCode");
            if(takeCode!=null){
                order.setTicketCode(takeCode.toString());
            }
            switch (putStatus) {
                case 2:
                case 3:
                    order.setHwStatus("出单中");
                    break;
                case 4:
                case 7:
                    order.setHwStatus("出餐成功");//（中间状态：出取餐码，后续有可能会转退款）
                    order.setStatus(Utils.STATUS_OVER);
                    break;
                case 8:
                    order.setHwStatus("配送中");
                    JSONObject courierInfoJson = new JSONObject();
//                    courierInfoJson.put("courierName", "");
//                    courierInfoJson.put("courierPhone", "");
                    courierInfoJson.put("courierLocationH5", (String) map.get("courierLocationH5"));
                    order.setCourierInfo(courierInfoJson.toJSONString());
                    break;
                case 9:
                    order.setHwStatus("已送达");
                    order.setStatus(Utils.STATUS_OVER);
                    break;
                case 6:
                    order.setHwStatus("餐单失败");//退款（完结状态）
//                    order.setStatus(Utils.STATUS_WAIT_REFUND);直接退款不在人工审核
                    wepayService.allRefund(order);
                    order.setStatus(Utils.STATUS_REFUNDED);
                    break;
                default:
                    throw new NotErrorException(1001,"没有匹配的异常状态");
            }
        }else {
            String callBackTag = (String) map.get("callBackTag");
            order.setRefundPrice((Double) map.get("refundAmount"));
            order.setHwOrderId((String) map.get("putOrderId"));
            Double refundAmount = (Double) map.get("refundAmount");
            Double salePrice = (Double) map.get("salePrice");
            if(refundAmount.doubleValue()==salePrice.doubleValue()) {//如果退款等于平台拿货价
                order.setRefundPrice(order.getTotalPrice());//设置应退款总金额为实付款
            }else {
                order.setRefundPrice(refundAmount);
            }
            switch (callBackTag) {
                case "SU":
                    order.setHwStatus("出餐成功");
                    order.setStatus(Utils.STATUS_OVER);
                    if (!"WaiMai".equals(order.getEatType())){//外卖部分接口也有不可用取餐码，星巴克没有up阶段，取餐码在此放置
                        order.setTicketCode((String) map.get("takeCode"));
                    }
                    break;
                case "UP":
                    order.setTicketCode((String) map.get("takeCode"));
                    break;
                case "RE":
                    //部分退款
                    order.setHwStatus("部分出餐");
                    order.setStatus(Utils.STATUS_WAIT_REFUND);
                    order.setRefundInfo((String)map.get("refundAll"));
                    break;
                case "DE":
                    order.setHwStatus("配送中");
                    JSONObject courierInfoJson = new JSONObject();
                    courierInfoJson.put("courierName", (String) map.get("courierName"));
                    courierInfoJson.put("courierPhone", (String) map.get("courierPhone"));
                    courierInfoJson.put("courierLocationH5", (String) map.get("courierLocationH5"));
                    order.setCourierInfo(courierInfoJson.toJSONString());
                    break;
                case "DE_SU":
                    order.setHwStatus("已送达");                    order.setStatus(Utils.STATUS_OVER);
                    order.setStatus(Utils.STATUS_OVER);
                    break;
                case "FA":
                    order.setHwStatus("出餐失败");
//                order.setStatus(Utils.STATUS_WAIT_REFUND);自动退款，不在人工审核
                    wepayService.allRefund(order);
                    order.setStatus(Utils.STATUS_REFUNDED);
//                JSONObject refundInfoJson = new JSONObject();
////                refundInfoJson.put("refundAll", (String) map.get("refundAll"));//设置待退款商品信息
//                refundInfoJson.put("refundTotalAmount", order.getTotalPrice());
//                refundInfoJson.put("refundedAmount", 0);//设置已退款总金额为0
//                refundInfoJson.put("refundedIdList", new ArrayList<String>());//设置已处理过的退款id
//                order.setRefundInfo(refundInfoJson.toJSONString());
                    break;
                default:
            }
        }
        myOrderService.updateById(order);
        HashMap<String, Object> respJson = new HashMap<>();
        respJson.put("rtnCode", "000000");
        respJson.put("rtnMsg", "成功!");
        return "OK";
    }
    //麻花的DY回调接口
    public String mhDYNotify(Map<String, Object> map) throws JsonProcessingException, IllegalAccessException, NoSuchFieldException, InstantiationException, ParseException {
        //查询订单
        MyOrder order = myOrderService.getById((String) map.get("outId"));
        String status = (String) map.get("status");
        switch (status) {
            case "drawSuccess":
                order.setHwStatus("已出票");
                order.setStatus(Utils.STATUS_OVER);
                //设置取票码
//                List tickets = (List) map.get("tickets");
                order.setTicketCode(JSON.toJSONString(map.get("tickets")));
                break;
            case "updateTicket":
                order.setHwStatus("更新票");
                break;

            case "drawClose":
                order.setHwStatus("出票失败");
                //退款
                wepayService.allRefund(order);
                order.setStatus(Utils.STATUS_REFUNDED);
                break;
            case "confirmSuccess":
                order.setHwStatus("确认收货");
                break;
            default:
        }
        myOrderService.updateById(order);
        HashMap<String, Object> respJson = new HashMap<>();
        respJson.put("rtnCode", "000000");
        respJson.put("rtnMsg", "成功!");
        return "OK";
    }

    @Override
    public R<MyOrder> searchOrder(MyOrder order) {
        String time = String.valueOf(new Date().getTime());
        Map<String, Object> argsMap = new HashMap<String, Object>();
        argsMap.put("outId", order.getId());
        String url = "";
        switch (order.getMovieName()) {
            case "奈雪的茶":
                url = "NX";
                break;
            case "星巴克":
                url = "XBK";
                break;
            case "肯德基":
                url = "KFC";
                break;
            case "麦当劳":
                url = "MCD";
                break;
            case "瑞幸咖啡":
                url = "LK";
                break;
            case "必胜客":
                url = "PZH";
                break;
            default:
                log.info("没有匹配异常结束");
                throw new NotErrorException(1001,"没有匹配异常结束");
        }
        url = "MH_" + url + "_QUERY";
        log.info("argsMap:{}", argsMap.toString());
        Map<String, Object> res = (Map<String, Object>) getData(argsMap, Utils.mhUrl.get(url), time);
        System.out.println("===========");
        log.info("searchOrder res:{}", res.toString());
        System.out.println("===========");
        if (!"000000".equals(res.get("rtnCode"))) {
            throw new NotErrorException(1008, res.get("rtnCode") + (String) res.get("rtnMsg"));
        }
        //修改订单状态
        Map<String, Object> rtnData = (Map<String, Object>) res.get("rtnData");
        log.info("searchOrder rtnData:{}", rtnData.toString());
        if("奈雪的茶".equals(order.getMovieName())){//奈雪的查询不一样
            Integer putStatus = (Integer) rtnData.get("putStatus");
            order.setRefundPrice((Double) rtnData.get("refundAmount"));
            Double refundAmount = (Double) rtnData.get("refundAmount");
            Double totalAmount = (Double) rtnData.get("totalAmount");
            if(refundAmount.doubleValue()==totalAmount.doubleValue()) {//如果退款等于平台拿货价
                order.setRefundPrice(order.getTotalPrice());//设置应退款总金额为实付款
            }else {
                order.setRefundPrice(refundAmount);
            }
            //如果取餐码有值，设置值
            Object takeCode = rtnData.get("takeCode");
            if(takeCode!=null){
                order.setTicketCode(takeCode.toString());
            }
            switch (putStatus) {
                case 2:
                case 3:
                    order.setHwStatus("出单中");

                    break;
                case 4:
                case 7:
                    order.setHwStatus("出餐成功");//（中间状态：出取餐码，后续有可能会转退款）
                    order.setStatus(Utils.STATUS_OVER);

                    break;
                case 8:
                    order.setHwStatus("配送中");
                    JSONObject courierInfoJson = new JSONObject();
//                    courierInfoJson.put("courierName", "");
//                    courierInfoJson.put("courierPhone", "");
                    courierInfoJson.put("courierLocationH5", (String) rtnData.get("courierLocationH5"));
                    order.setCourierInfo(courierInfoJson.toJSONString());
                    break;
                case 9:
                    order.setHwStatus("已送达");
                    order.setStatus(Utils.STATUS_OVER);

                    break;
                case 6:
                    order.setHwStatus("餐单失败");//退款（完结状态）
//                    order.setStatus(Utils.STATUS_WAIT_REFUND);直接退款不在人工审核
                    wepayService.allRefund(order);
                    order.setStatus(Utils.STATUS_REFUNDED);
                    break;
                default:
                    throw new NotErrorException(1001,"没有匹配的异常状态");
            }
        }else{
            String status = (String) rtnData.get("status");
            order.setRefundPrice((Double) rtnData.get("refundAmount"));
            Double refundAmount = (Double) rtnData.get("refundAmount");
            Double salePrice = (Double) rtnData.get("salePrice");
            if(refundAmount.doubleValue()==salePrice.doubleValue()) {//如果退款等于平台拿货价
                order.setRefundPrice(order.getTotalPrice());//设置应退款总金额为实付款
            }else {
                order.setRefundPrice(refundAmount);
            }
            //如果取餐码有值，设置值
            Object takeinfo = rtnData.get("takeinfo");
            if(takeinfo!=null){
                order.setTicketCode(takeinfo.toString());
            }
            switch (status) {
                case "doing":
                    order.setHwStatus("出单中");
                    break;
                case "success":
                    order.setHwStatus("出餐成功");//（中间状态：出取餐码，后续有可能会转退款）
                    order.setStatus(Utils.STATUS_OVER);
                    break;
                case "deliverying":
                    order.setHwStatus("配送中");
                    JSONObject courierInfoJson = new JSONObject();
//                    courierInfoJson.put("courierName", "");
//                    courierInfoJson.put("courierPhone", "");
                    courierInfoJson.put("courierLocationH5", (String) rtnData.get("courierLocationH5"));
                    order.setCourierInfo(courierInfoJson.toJSONString());
                    break;
                case "deliveryed":
                    order.setHwStatus("已送达");
                    order.setStatus(Utils.STATUS_OVER);

                    break;
                case "close":
                    order.setHwStatus("出餐失败");//退款（完结状态）
                    //                order.setStatus(Utils.STATUS_WAIT_REFUND);自动退款，不在人工审核
                    wepayService.allRefund(order);
                    order.setStatus(Utils.STATUS_REFUNDED);
                    break;
                default:
            }
            //如果有部分退款
            List<Map> refundAll =(List<Map>)rtnData.get("refundAll");
            if(!refundAll.isEmpty()){
                //部分退款
                order.setHwStatus("部分出餐");
                order.setStatus(Utils.STATUS_WAIT_REFUND);
                order.setRefundInfo(JSON.toJSONString(rtnData.get("refundAll")));
            }
        }
        myOrderService.updateById(order);
        return R.success(order);
    }

    @Override
    public void createDYOrder(MyOrder order) {
        String time = String.valueOf(new Date().getTime());
        Map<String, Object> argsMap = new HashMap<String, Object>();
        String url = "MH_MAHUA_BUY";
        argsMap.put("outId", order.getId().toString());
        argsMap.put("showId", order.getRestaurantId());
        List<Map> buySeats = JSON.parseArray(order.getSeat(), Map.class);
        argsMap.put("buySeats", buySeats);//待处理
        argsMap.put("callBackUrl", notifyUrl);
        argsMap.put("acceptChangeseat", "0");
        log.info("argsMap:{}", argsMap.toString());
        Map<String, Object> res = (Map<String, Object>) getData(argsMap, Utils.mhUrl.get(url), time);
        if (!"000000".equals(res.get("rtnCode"))) {
            //自动退款，不在人工审核
            order.setHwStatus("出单失败");
            order.setStatus(Utils.STATUS_REFUNDED);
            wepayService.allRefund(order);
            myOrderService.updateById(order);
            throw new NotErrorException(1008, res.get("rtnCode") + (String) res.get("rtnMsg"));
        } else {
           order.setHwStatus("出票中");
           myOrderService.updateById(order);
        }
    }
}
